package com.boot.security.server.controller.mffl;

import com.boot.security.server.dao.mffl.MfflTypeDao;
import com.boot.security.server.dto.LayuiFile;
import com.boot.security.server.model.FileInfo;
import com.boot.security.server.model.mffl.MfflType;
import com.boot.security.server.service.FileService;
import com.boot.security.server.utils.FileUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "公共功能")
@RestController
@RequestMapping("/mffl")
public class Mfflpublic {

    @Autowired
    private MfflTypeDao mfflTypeDao;

    @Autowired
    private FileService fileService;

    //公共功能业务
    @Autowired
    private publicService publicService;

    @Value("${files.path}")
    private String imageth;

    @Value("${upload.imgType}")
    private String uploadImgType;
    @Value("${upload.type}")
    private String uploadType;


    @GetMapping("/getserviceidtype")
    @ApiOperation(value = "获取咨询类型")
    public ReturnBean getServiceidType(@ApiParam(required = true, name = "serviceid", value = "类型对应的服务id(1是专业/免费咨询分类，2是律师函，4是合同审核，5是合同定制，7资讯类型)") @RequestParam String serviceid) {
        ReturnBean returnBean = new ReturnBean();
        List<MfflType> consultationType = mfflTypeDao.getConsultationType(Integer.valueOf(serviceid));
        if (consultationType.size() != 0 && consultationType != null) {
            returnBean.setDatas(consultationType);
        } else {
            returnBean.setReturnBean("104");
        }
        return returnBean;
    }


    @PostMapping("/uploadimagefile")
    @ApiOperation(value = "图片上传")
    public ReturnBean uploadImageFile(@ApiParam(name = "file", value = "图片", required = true) @RequestParam MultipartFile file,
                                      @ApiParam(name = "type", value = "类型，image或不传为图片，file为文件。", required = false) @RequestParam(required = false) String type) throws IOException {
        if (!publicService.uploadImageSize(file.getSize() / 1024)) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("135");
            return returnBean;
        }

        String[] uploadImgTypeGroup;
        if (StringUtils.isEmpty(type) || type.equals("image")) {
            uploadImgTypeGroup = uploadImgType.split(",");
        } else if (type.equals("file")) {
            uploadImgTypeGroup = uploadType.split(",");
        } else {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("143");
            return returnBean;
        }

        String fileName = file.getOriginalFilename();
        int st1 = fileName.lastIndexOf(".");
        String suffix1 = fileName.substring(st1);
        boolean bo = false;
        for (int i = 0; i < uploadImgTypeGroup.length; i++) {
            if (suffix1.indexOf(uploadImgTypeGroup[i]) == 0) {
                bo = true;
            }
        }

        if (!bo) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("136");
            return returnBean;
        }


        FileInfo fileInfo = fileService.save(file);
        String path = fileInfo.getPath();
        File imageFile = new File(path);

        if (StringUtils.isEmpty(type) || type.equals("image")) {
            //800*450
            Image image = null;
//        try{
            image = ImageIO.read(imageFile);
//        }catch (Exception e){
//            e.printStackTrace();
//            ReturnBean returnBean = new ReturnBean();
//            returnBean.setReturnBean("111");
//            return returnBean;
//        }

            int st = path.indexOf(".");
            String suffix = path.substring(st);
            BufferedImage image800 = FileUtil.compressImageScadvert(image, 800, 450, suffix);

            String n800Path = path.substring(0, st) + "_med" + path.substring(st);
            ImageIO.write(image800, path.substring(st + 1), new File(n800Path));

            //300*300
            BufferedImage image400 = FileUtil.compressImageScadvert(image, 300, 300, suffix);
            int image400Width = image400.getWidth();
            if (image400Width > 400) {
                int xy = image400Width - 400;
                int xynum = xy / 2;
                image400 = image400.getSubimage(xynum, 0, 400, 400);
            }
            String n400Path = path.substring(0, st) + "_min" + path.substring(st);
            ImageIO.write(image400, path.substring(st + 1), new File(n400Path));
            Map<String, Object> map = new HashMap<>();
            map.put("id", fileInfo.getId());
            map.put("max", fileInfo.getUrl());
            map.put("med", n800Path.replace(imageth, ""));
            map.put("min", n400Path.replace(imageth, ""));
            return new ReturnBean("200", map, "OK");
        }
        return new ReturnBean("200", path, "OK");
    }

    @GetMapping(value = "getapplicationinfo")
    @ApiOperation(value = "获取移动端版本信息")
    public ReturnBean getApplicationInfo(@ApiParam(name = "applicationname", value = "应用名称（安卓填写Android/苹果填写IOS）", required = true) @RequestParam String applicationname,
                                         @ApiParam(name = "code", value = "当前版本号", required = true) @RequestParam String code) {
        if (StringUtils.isEmpty(applicationname)) {
            return new ReturnBean("201", "应用名称,不能为空");
        }
        if (StringUtils.isEmpty(code)) {
            return new ReturnBean("201", "当前版本号,不能为空");
        }
        if (!("Android".equals(applicationname) || "IOS".equals(applicationname))) {
            return new ReturnBean("201", "未知应用名称，暂时未开通");
        }
        return publicService.getApplicationInfo(applicationname, code);
    }


    @GetMapping(value = "getaboutusinfo")
    @ApiOperation(value = "获取联系我们信息")
    public ReturnBean getContactusInfo() {
        return publicService.getContactusInfo();
    }
}
